var express = require('express');
var router = express.Router();
//引入数据库包
var db = require("../models/MySql.js");

/* GET users listing. */
// router.get('/', function(req, res, next) {
//   res.send('respond with a resource');
// });

/**
 * 查询列表页
 */
router.get('/', function (req, res, next) {
    db.query('select * from userinfo', function (err, rows) {
        if (err) {
            res.render('rootUser', {title: 'Express', datas: []});  // this renders "views/users.html"
        } else {
            res.render('rootUser', {title: 'Express', datas: rows});
        }
    })
});
/**
 * 新增页面跳转
 */

router.get('/add', function (req, res) {
    res.render('add');
});
router.post('/add', function (req, res) {
    var name = req.body.username;
    var status = req.body.status;
    db.query("insert into userinfo(username,status) values('" + name + "'," + status + ")", function (err, rows) {
        if (err) {
            res.end('新增失败：' + err);
        } else {
            res.redirect('/rootUser');
        }
    })
});

/**
 * 删
 */
router.get('/del/:id', function (req, res) {
    var id = req.params.id;
    db.query("delete from userinfo where id=" + id, function (err, rows) {
        if (err) {
            res.end('删除失败：' + err)
        } else {
            res.redirect('/rootUser')
        }
    });
});
/**
 * 修改
 */
router.get('/toUpdate/:id', function (req, res) {
    var id = req.params.id;
    db.query("select * from userinfo where id=" + id, function (err, rows) {
        if (err) {
            res.end('修改页面跳转失败：' + err);
        } else {
            res.render("update", {datas: rows});       //直接跳转
        }
    });
});
router.post('/update', function (req, res) {
    var id = req.body.id;
    var name = req.body.username;
    var status = req.body.status;
    db.query("update userinfo set username='" + name + "',status='" + age + "' where id=" + id, function (err, rows) {
        if (err) {
            res.end('修改失败：' + err);
        } else {
            res.redirect('/rootUser');
        }
    });
});
/**
 * 查询
 */
router.post('/search', function (req, res) {
    var name = req.body.s_name;
    var status = req.body.s_status;

    var sql = "select * from userinfo";

    if (name) {
        sql += " and name='" + name + "' ";
    }

    if (status) {
        sql += " and status=" + status + " ";
    }
    sql = sql.replace("and","where");
    db.query(sql, function (err, rows) {
        if (err) {
            res.end("查询失败：", err)
        } else {
            res.render("rootUser", {title: 'Express', datas: rows, s_name: name, s_status: status});
        }
    });
});

module.exports = router;
